package cn.lingyangwl.agile.pay.pay.process.transfer;

import cn.lingyangwl.agile.pay.common.exception.ChannelException;
import cn.lingyangwl.agile.pay.common.service.PayInterfaceConfigService;
import cn.lingyangwl.agile.pay.common.service.TransferOrderService;
import cn.lingyangwl.agile.pay.common.utils.AmountUtils;
import cn.lingyangwl.agile.pay.pay.channel.AbstractTransferService;
import cn.lingyangwl.agile.pay.pay.channel.ITransferService;
import cn.lingyangwl.agile.pay.pay.model.bo.MchAppConfigContext;
import cn.lingyangwl.agile.pay.pay.model.rqrs.ChannelRetMsgExt;
import cn.lingyangwl.agile.pay.pay.model.rqrs.transfer.TransferOrderRQ;
import cn.lingyangwl.agile.pay.pay.model.rqrs.transfer.TransferOrderRS;
import cn.lingyangwl.agile.pay.pay.service.ConfigContextQueryService;
import cn.lingyangwl.agile.pay.pay.service.PayMchNotifyService;
import cn.lingyangwl.framework.core.response.Resp;
import cn.lingyangwl.framework.core.utils.IpUtils;
import cn.lingyangwl.framework.tool.core.StringUtils;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import cn.lingyangwl.agile.pay.model.entity.MchApp;
import cn.lingyangwl.agile.pay.model.entity.MchInfo;
import cn.lingyangwl.agile.pay.model.entity.TransferOrder;
import com.github.yitter.idgen.YitIdHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author shenguangyang
 */
@Slf4j
@Service
public class TransferOrderProcess {
    @Resource
    private ConfigContextQueryService configContextQueryService;
    @Resource
    private TransferOrderService transferOrderService;
    @Resource
    private PayInterfaceConfigService payInterfaceConfigService;
    @Resource
    private PayMchNotifyService payMchNotifyService;


    /**
     * 转账
     */
    public Resp<?> transferOrder(TransferOrderRQ bizRQ) {
        TransferOrder transferOrder = null;
        try {

            String mchNo = bizRQ.getMchNo();
            String appId = bizRQ.getAppId();
            String ifCode = bizRQ.getIfCode();

            // 商户订单号是否重复
            if (transferOrderService.count(TransferOrder.lqw().eq(TransferOrder::getMchNo, mchNo).eq(TransferOrder::getMchOrderNo, bizRQ.getMchOrderNo())) > 0) {
                throw new BizException("商户订单[" + bizRQ.getMchOrderNo() + "]已存在");
            }

            if (StringUtils.isNotEmpty(bizRQ.getNotifyUrl()) && !StringUtils.isAvailableUrl(bizRQ.getNotifyUrl())) {
                throw new BizException("异步通知地址协议仅支持http:// 或 https:// !");
            }

            // 商户配置信息
            MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(mchNo, appId);
            if (mchAppConfigContext == null) {
                throw new BizException("获取商户应用信息失败");
            }

            MchApp mchApp = mchAppConfigContext.getMchApp();
            MchInfo mchInfo = mchAppConfigContext.getMchInfo();

            // 是否已正确配置
            if (!payInterfaceConfigService.mchAppHasAvailableIfCode(appId, ifCode)) {
                throw new BizException("应用未开通此接口配置!");
            }


            ITransferService transferService = AbstractTransferService.getService(ifCode);
            if (transferService == null) {
                throw new BizException("无此转账通道接口");
            }

            if (!transferService.isSupport(bizRQ.getEntryType())) {
                throw new BizException("该接口不支持该入账方式");
            }

            transferOrder = genTransferOrder(bizRQ, mchInfo, mchApp, ifCode);

            //预先校验
            String errMsg = transferService.preCheck(bizRQ, transferOrder);
            if (StringUtils.isNotEmpty(errMsg)) {
                throw new BizException(errMsg);
            }

            // 入库
            transferOrderService.save(transferOrder);

            // 调起上游接口
            ChannelRetMsgExt channelRetMsgExt = transferService.transfer(bizRQ, transferOrder, mchAppConfigContext);

            //处理退款单状态
            this.processChannelMsg(channelRetMsgExt, transferOrder);

            TransferOrderRS bizRes = TransferOrderRS.buildByRecord(transferOrder);
            return Resp.ok(bizRes);
        } catch (BizException e) {
            return Resp.fail(e.getMessage());

        } catch (ChannelException e) {

            //处理上游返回数据
            this.processChannelMsg(e.getChannelRetMsgExt(), transferOrder);

            if (e.getChannelRetMsgExt().getChannelState() == ChannelRetMsgExt.ChannelState.SYS_ERROR) {
                return Resp.fail(e.getMessage());
            }

            TransferOrderRS bizRes = TransferOrderRS.buildByRecord(transferOrder);
            return Resp.ok(bizRes);

        } catch (Exception e) {
            log.error("系统异常: ", e);
            return Resp.fail("系统异常");
        }
    }


    private TransferOrder genTransferOrder(TransferOrderRQ rq, MchInfo mchInfo, MchApp mchApp, String ifCode) {

        TransferOrder transferOrder = new TransferOrder();
        transferOrder.setTransferNo(YitIdHelper.nextId() + ""); //生成转账订单号
        transferOrder.setMchNo(mchInfo.getMchNo()); //商户号
        transferOrder.setIsvNo(mchInfo.getIsvNo()); //服务商号
        transferOrder.setAppId(mchApp.getId()); //商户应用appId
        transferOrder.setMchName(mchInfo.getMchShortName()); //商户名称（简称）
        transferOrder.setMchType(mchInfo.getType()); //商户类型
        transferOrder.setMchOrderNo(rq.getMchOrderNo()); //商户订单号
        transferOrder.setIfCode(ifCode); //接口代码
        transferOrder.setEntryType(rq.getEntryType()); //入账方式
        transferOrder.setAmount(AmountUtils.fenToYuan(rq.getAmount())); //订单金额
        transferOrder.setCurrency(rq.getCurrency()); //币种
        transferOrder.setClientIp(StringUtils.defaultIfEmpty(rq.getClientIp(), IpUtils.getHostIp())); //客户端IP
        transferOrder.setStatus(TransferOrder.STATE_INIT); //订单状态, 默认订单生成状态
        transferOrder.setAccountNo(rq.getAccountNo()); //收款账号
        transferOrder.setAccountName(rq.getAccountName()); //账户姓名
        transferOrder.setBankName(rq.getBankName()); //银行名称
        transferOrder.setTransferDesc(rq.getTransferDesc()); //转账备注
        transferOrder.setExtParam(rq.getExtParam()); //商户扩展参数
        transferOrder.setNotifyUrl(rq.getNotifyUrl()); //异步通知地址
        transferOrder.setCreatedAt(new Date()); //订单创建时间
        return transferOrder;

    }


    /**
     * 处理返回的渠道信息，并更新订单状态
     * TransferOrder将对部分信息进行 赋值操作。
     */
    private void processChannelMsg(ChannelRetMsgExt channelRetMsgExt, TransferOrder transferOrder) {

        //对象为空 || 上游返回状态为空， 则无需操作
        if (channelRetMsgExt == null || channelRetMsgExt.getChannelState() == null) {
            return;
        }

        String transferNo = transferOrder.getTransferNo();

        //明确成功
        if (ChannelRetMsgExt.ChannelState.CONFIRM_SUCCESS == channelRetMsgExt.getChannelState()) {

            this.updateInitOrderStateThrowException(TransferOrder.STATE_SUCCESS, transferOrder, channelRetMsgExt);
            payMchNotifyService.transferOrderNotify(transferOrder);

            //明确失败
        } else if (ChannelRetMsgExt.ChannelState.CONFIRM_FAIL == channelRetMsgExt.getChannelState()) {

            this.updateInitOrderStateThrowException(TransferOrder.STATE_FAIL, transferOrder, channelRetMsgExt);
            payMchNotifyService.transferOrderNotify(transferOrder);

            // 上游处理中 || 未知 || 上游接口返回异常  订单为支付中状态
        } else if (ChannelRetMsgExt.ChannelState.WAITING == channelRetMsgExt.getChannelState() ||
                ChannelRetMsgExt.ChannelState.UNKNOWN == channelRetMsgExt.getChannelState() ||
                ChannelRetMsgExt.ChannelState.API_RET_ERROR == channelRetMsgExt.getChannelState()

        ) {
            this.updateInitOrderStateThrowException(TransferOrder.STATE_ING, transferOrder, channelRetMsgExt);

            // 系统异常：  订单不再处理。  为： 生成状态
        } else if (ChannelRetMsgExt.ChannelState.SYS_ERROR == channelRetMsgExt.getChannelState()) {

        } else {

            throw new BizException("ChannelState 返回异常！");
        }

    }


    /**
     * 更新订单状态 --> 订单生成--> 其他状态  (向外抛出异常)
     */
    private void updateInitOrderStateThrowException(String orderStatus, TransferOrder transferOrder, ChannelRetMsgExt channelRetMsgExt) {

        transferOrder.setStatus(orderStatus);
        transferOrder.setChannelOrderNo(channelRetMsgExt.getChannelOrderId());
        transferOrder.setErrCode(channelRetMsgExt.getChannelErrCode());
        transferOrder.setErrMsg(channelRetMsgExt.getChannelErrMsg());


        boolean isSuccess = transferOrderService.updateInit2Ing(transferOrder.getTransferNo());
        if (!isSuccess) {
            throw new BizException("更新转账订单异常!");
        }

        isSuccess = transferOrderService.updateIng2SuccessOrFail(transferOrder.getTransferNo(), transferOrder.getStatus(),
                channelRetMsgExt.getChannelOrderId(), channelRetMsgExt.getChannelErrCode(), channelRetMsgExt.getChannelErrMsg());
        if (!isSuccess) {
            throw new BizException("更新转账订单异常!");
        }
    }
}
